<?php

/**
 * @file
 * Plugin to provide access control based on device type
 * This is provided by context mobile detect.
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t('Device Detection'),
  'description' => t('Check for Device (Mobile, Tabled or Desktop)'),
  'callback' => 'context_mobile_detect_ctools_access_check',
  'default' => array('negate' => 0),
  'settings form' => 'context_mobile_detect_ctools_access_settings',
  'summary' => 'context_mobile_detect_ctools_access_summary',
);

/**
 * Settings form for the 'context mobile detect' access plugin
 */
function context_mobile_detect_ctools_access_settings($form, &$form_state, $conf) {
  $options = context_mobile_detect_options();
  $form['settings']['type'] = array(
    '#type' => 'radios',
    '#description' => t("Check to see if the detected device is one of those. With the reverse option you can also check for any other device type but not the selected."),
    '#options' => $options,
    '#default_value' => $conf['type'],
  );
  return $form;
}

/**
 * Check for access.
 */
function context_mobile_detect_ctools_access_check($conf, $context) {
  // Should we really load a "_context_mobile_detect_detect" function here?
  // TODO: Check how we should load the detection
  $data = _context_mobile_detect_detect(FALSE);

  /**
   * TODO: $data["device_type"] seems to be always 0
   * Anyway we need only device here.
   */
  //dpm("device detected is: " . $data);

  // Load possible options for debug message.
  $options = context_mobile_detect_options();

  // Return if it is the needed device and giving access to it.
  if ($data["device"] == $conf["type"]) {
    //dpm("You are using the needed device: " . $options[$data["device"]]);
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Provide a summary description about which type of device is needed.
 */
function context_mobile_detect_ctools_access_summary($conf, $context) {
  $options = context_mobile_detect_options();
  return t('Detected @device', array("@device" => $options[$conf["type"]]));
}

/**
 * Helper function for the available options
 */
function context_mobile_detect_options() {
  $options = array(
    1 => t('Mobile Device'),
    2 => t('Tablet Device'),
    3 => t('Desktop Device')
  );
  return $options;
}
